#include "goose61850subscriber.h"

static void gooseListener(GooseSubscriber subscriber, void* parameter)
{
    printf("GOOSE event:\n");
    printf("  stNum: %u sqNum: %u\n", GooseSubscriber_getStNum(subscriber),
            GooseSubscriber_getSqNum(subscriber));
    printf("  timeToLive: %u\n", GooseSubscriber_getTimeAllowedToLive(subscriber));

    uint64_t timestamp = GooseSubscriber_getTimestamp(subscriber);

    printf("  timestamp: %u.%u\n", (uint32_t) (timestamp / 1000), (uint32_t) (timestamp % 1000));
    printf("  message is %s\n", GooseSubscriber_isValid(subscriber) ? "valid" : "INVALID");

    MmsValue* values = GooseSubscriber_getDataSetValues(subscriber);

    char buffer[1024];

    MmsValue_printToBuffer(values, buffer, 1024);

    printf("  allData: %s\n", buffer);
}

Goose61850Subscriber::Goose61850Subscriber()
{
//    setInterface("lo");
    m_receiver = GooseReceiver_create();
}

Goose61850Subscriber::~Goose61850Subscriber()
{

    GooseReceiver_stop(m_receiver);

    GooseReceiver_destroy(m_receiver);
}

void Goose61850Subscriber::setInterface(QString t)
{
    m_interfaceStr = t;

    GooseReceiver_stop(m_receiver);

    GooseReceiver_setInterfaceId(m_receiver, t.toLatin1().data());

    GooseSubscriber subscriber = GooseSubscriber_create("simpleIOGenericIO/LLN0$GO$gcbAnalogValues", NULL);

    uint8_t dstMac[6] = {0x01,0x0c,0xcd,0x01,0x00,0x01};
    GooseSubscriber_setDstMac(subscriber, dstMac);
    GooseSubscriber_setAppId(subscriber, 1000);

    GooseSubscriber_setListener(subscriber, gooseListener, NULL);

    GooseReceiver_addSubscriber(m_receiver, subscriber);

    GooseReceiver_start(m_receiver);

    if (GooseReceiver_isRunning(m_receiver)) {
    }
    else{
        exit(-1);
        printf("Failed to start GOOSE subscriber. Reason can be that the Ethernet interface doesn't exist or root permission are required.\n");
    }
}
